package com.zxq.ai.domain.service;

import com.zxq.common.middleware.DistributedID;
import com.zxq.common.utils.DateUtil;
import com.zxq.common.utils.PhoneNoUtil;
import com.zxq.ai.domain.enums.UserType;
import com.zxq.ai.domain.exception.UserTypeInvalidException;
import com.zxq.ai.domain.user.User;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.Objects;


@Service
public class UserDomain {

    @Resource
    private DistributedID distributedID;

    /**
     * 生成实例
     * @param userType
     * @param phoneNo
     * @param userName
     */
    public User generateInstance(UserType userType, String phoneNo, String userName) {

        if (Objects.isNull(userType)) {
            throw new UserTypeInvalidException("userType不能为空");
        }
        if (PhoneNoUtil.isValidPhoneNumber(phoneNo)) {
            throw new UserTypeInvalidException(String.format("手机号[%s]格式不正确", phoneNo));
        }
        if (StringUtils.isBlank(userName)) {
            userName = userType.getDesc() + PhoneNoUtil.getLastFourDigits(phoneNo);
        }

        Long userId = distributedID.nextId();

        User user = User.builder()
                .userId(userId)
                .userType(userType)
                .phoneNo(phoneNo)
                .userName(userName)
                .createAt(DateUtil.millis())
                .updateAt(DateUtil.millis())
                .createBy("system")
                .createBy("system")
                .build();

        return user;
    }

}
